//
//  Product.m
//  TestOCRedux
//
//  Created by Hotacool on 2019/2/25.
//  Copyright © 2019 Hotacool. All rights reserved.
//

#import "Product.h"
#import "objc/runtime.h"

@implementation Product
- (NSString *)description {
    return @{@"count": @(self.count), @"consume": @(self.consume)}.description;
}
#pragma mark -- encode
- (void)encodeWithCoder:(NSCoder *)coder {
    [self code:YES coder:coder];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        [self code:NO coder:aDecoder];
    }
    return self;
}

- (void)code:(BOOL)isEncode coder:(NSCoder *)coder {
    unsigned int outCount = 0;
    Ivar *ivars = class_copyIvarList([self class], &outCount);
    for (int i = 0; i<outCount; i++) {
        Ivar ivar = ivars[i];
        const char * name = ivar_getName(ivar);
        NSString *key = [NSString stringWithUTF8String:name];
        id value;
        if (isEncode) {
            value = [self valueForKey:key];
            [coder encodeObject:value forKey:key];
        } else {
            value = [coder decodeObjectForKey:key];
            [self setValue:value forKey:key];
        }
    }
    free(ivars);
}
@end
